package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

//pojo实体类
//@WebServlet("/hello")//目前一个类只能请求一个地址，只能响应/hello
@WebServlet(urlPatterns = {"/user"})//请求类是唯一的，不能请求相同的地址
//响应注解名称，在网页后加注解名称，就可以访问这个servlet
public class UserServlet extends HttpServlet {
  //  alt+insert  选择第三个，然后选择第二个和第五个
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> users=new ArrayList<>();//用户数据存在集合中
        //jdbc 操作数据库 查询
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接(url username password)
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            Connection connection = DriverManager.getConnection(url, "root", "20050324");
//           if(connection!=null){
//               System.out.println("连接成功");
//           }测试成功后注释掉
            //3.写sql
            String sql="select * from sys_user";
            //4.预编译sql
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            //5.有参数设置参数
            //6.执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
            //7.遍历结果集
            while (resultSet.next()){
                User user=new User();
                user.setId(resultSet.getInt(1));//关联到对应属性
                user.setName(resultSet.getString(2));
                user.setPass(resultSet.getString(3));//关联到对应属性
                users.add(user);//把对象添加到集合中
//                int id = resultSet.getInt(1);
//                String name = resultSet.getString(2);
//                String pass = resultSet.getString(3);
//                System.out.println(id+"---"+name+"---"+pass);
            }
            //8.关闭资源
            resultSet.close();//修改操作会多这一步
            preparedStatement.close();
            connection.close();

            //把集合中的数据存储到作用域中
            req.setAttribute("users",users);//支持key value
            req.getRequestDispatcher("/user.jsp").forward(req,resp);//打开页面，转发打开，请求地址不会变。不会被非法拦截
            //加入后更安全
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }
    }

